package global.filter;

import global.Constants;
import global.security.AuthenticatorHolder;
import global.security.ClientSession;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;
import util.ServletHelp;
import util.StringUtils;

/**
 * 用户登录用过滤器类.
 * <p>
 * 创建日期：2010-07-01<br>
 * 创建人：Xiyt<br>
 * 修改日期：<br>
 * 修改人：<br>
 * 修改内容：<br>
 * 
 * @author Xiyt
 * @version 1.0
 */
public class LoginFilter implements Filter {
	
	/** 不过滤的URl */
	private String unfilteredURIs;
	
	/** 登录用URl */
	private String loginPageUrls;

	public void init(FilterConfig config) throws ServletException {
		unfilteredURIs = jointString(config.getInitParameter("unfilteredURIs"));
		loginPageUrls = jointString(config.getInitParameter("loginPageUrls"));
	}

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = request.getSession(false);
		String requestURI = request.getRequestURI();
		String userId = request.getParameter("userId");
		String actionType = request.getParameter("actionType");
		
		// 如果是不做检查的资源直接跳过。
		if (requestURI.matches(unfilteredURIs)) {
			chain.doFilter(request, response);
			return;
		}
		if(requestURI.matches(loginPageUrls) || requestURI.contains("resetPwd.jsp") || requestURI.contains("register.jsp")){
			// 加载配置文件
			InputStream is = Constants.class.getClassLoader().getResourceAsStream("../setting.properties");
			Properties p = new Properties();
			try {
				p.load(is);
				// 是否开放注册
				request.setAttribute("openRegister", p.getProperty("setting.openRegister"));
			}finally{
				is.close();
			}
			chain.doFilter(request, response);
			return;
		}
		
		if(!"UPLOAD_ACTION".equals(actionType)){// 由于采用flash上传文件时，会生成新的Session，所以文件上传时不做session判断
			// 客户端Session类
			ClientSession cs = null;
			if(null != session){
				cs = (ClientSession) session.getAttribute("CLIENT_SESSION");
			}
			if(null == session || null == cs){
				if(requestURI.matches(loginPageUrls)){
					chain.doFilter(request, response);
					return;
				}else{
					if(requestURI.contains("Action.do")){
						// 返回结果
						JSONObject res = new JSONObject();
						res.put("success", false);
						res.put("message", Constants.E_LOGIN_TIMEOUT);
						res.put("exceptionMsg", Constants.E_LOGIN_TIMEOUT);
						ServletHelp.outRequestForJson(request, response, res.toString());
						return;
					}else{
						response.sendRedirect(request.getContextPath()+"/websrc/page/common/sessionError.jsp");
						return;
					}
				}
			}else{
				AuthenticatorHolder.setClientSession(cs);
				if(requestURI.matches(loginPageUrls)){// 防止重复登录
					response.sendRedirect(request.getContextPath()+"/websrc/page/index.jsp");
					return;
				}
			}
		}else{// 文件上传时,只做登录用户ID的判断
			if(StringUtils.isNotEmpty(userId)){
				ClientSession cs = new ClientSession();
				cs.setUserId(userId);
				AuthenticatorHolder.setClientSession(cs);
			}else{
				response.sendRedirect(request.getContextPath()+"/websrc/page/common/sessionError.jsp");
				return;
			}
		}
		chain.doFilter(request, response);
	}

	public void destroy() {
	}
	
	protected String jointString(String str) {
		StringBuffer buf = new StringBuffer();
		for (StringTokenizer st = new StringTokenizer(str != null ? str : "",
				"\n", false); st.hasMoreTokens(); buf.append(st.nextToken()
				.trim()))
			;
		return buf.toString();
	}
}
